import React, { Component } from "react";
import CategoryFrom from "./components/category-from";
import {
  Space,
  Table,
  Button,
  Row,
  Col,
  Modal,
  Switch,
  Popconfirm,
  message,
} from "antd";
import { courseDel, courseGet } from "../../api/course";
import { categoryData } from "../../utils/tools";

const columns = [
  {
    title: "类目级别",
    dataIndex: "parent",
    key: "parent",
    render: (text) => {
      return text == "0-0" ? "顶级目录" : "子级目录";
    },
  },
  {
    title: "类目名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "是否上架",
    dataIndex: "grounding",
    key: "grounding",
    render: (text) => <Switch defaultChecked checked={text} disabled />,
  },
  {
    title: "操作",
    key: "action",
    render: (_, record) => (
      <Space size="middle">
        <Button type="primary" size="small">
          编辑
        </Button>
        <Popconfirm
          title="删除"
          description="确认要删除这条数据吗？"
          onConfirm={() => {
            handleDel(record.objectId);
          }}
          onCancel={cancel}
          okText="Yes"
          cancelText="No"
        >
          <Button type="primary" danger size="small">
            删除
          </Button>
        </Popconfirm>
      </Space>
    ),
  },
];
const handleDel = (id) => {
  courseDel(id);
  message.success("删除成功");
};
const cancel = () => {
  message.error("取消操作");
};
export default class Category extends Component {
  state = {
    modalOpen: false,
    courseList: [],
  };
  componentDidMount = () => {
    courseGet().then((res) => {
      const { results } = res.data;
      let courseList = categoryData(results);
      this.setState({
        courseList,
      });
    });
  };

  showModal = (bool) => {
    this.setState({
      modalOpen: bool,
    });
  };
  handleFinish = (bool) => {
    this.setState({
      modalOpen: bool,
    });
  };
  render() {
    const { modalOpen } = this.state;
    return (
      <div>
        <Row justify="end">
          <Col span={3}>
            <Button
              type="primary"
              onClick={() => {
                this.showModal(true);
              }}
            >
              增加分类
            </Button>
          </Col>
        </Row>
        <Modal
          title="增加分类"
          open={modalOpen}
          onOk={() => {
            this.showModal(false);
          }}
          onCancel={() => {
            this.showModal(false);
          }}
          footer={null}
        >
          <CategoryFrom handleFinish={this.handleFinish}></CategoryFrom>
        </Modal>

        <Table
          columns={columns}
          dataSource={this.state.courseList}
          rowKey="objectId"
        />
      </div>
    );
  }
}
